package org.openoa.antreport.config;

import com.bstek.ureport.definition.datasource.BuildinDatasource;
import com.bstek.ureport.definition.datasource.DataSourceFactory;
import com.zaxxer.hikari.HikariDataSource;
import jdk.net.SocketFlow;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.bind.Bindable;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.boot.context.properties.source.ConfigurationPropertySource;
import org.springframework.boot.context.properties.source.ConfigurationPropertySources;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
import java.util.Map;

/**
 * Ureport 数据源
 *
 * @author 
 */

/**
 * 如果仅仅是一个简单demo没有问题,如果是一个复杂的项目往往不是通过默认配置得到的数据源(常见的mybatis plus dynamic datasource,这时候为了保持数据源一致就要配置一下)
 */
@Slf4j
@Configuration
public class AntReportDataSourceFactory implements DataSourceFactory {
    @Autowired
    private Environment environment;
    @Override
    public DataSource createAndGetDatasource() {
        String prefix = "spring.datasource";
        Iterable<ConfigurationPropertySource> sources = ConfigurationPropertySources.get(environment);
        Binder binder = new Binder(sources);
        DataSourceProperties dataSourceProperties = binder.bind(prefix, Bindable.of(DataSourceProperties.class))
                .orElseThrow(() -> new IllegalStateException("Failed to bind datasource properties"));
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(dataSourceProperties.getUrl());
        dataSource.setUsername(dataSourceProperties.getUsername());
        dataSource.setPassword(dataSourceProperties.getPassword());
        dataSource.setMaximumPoolSize(10);
        dataSource.setMinimumIdle(2);
        return dataSource;
    }
}
